<template>
  <div class="components-list">
    <draggable
      class="components-draggable"
      :list="modelVal"
      draggable=".components-item"
      :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
      :sort="false"
      :clone="cloneComponent"
    >
      <div
        class="components-item"
        v-for="(element, index) in modelVal"
        :key="index"
        @click="select(element)"
      >
        <div class="components-body">
          {{ element.label }}
        </div>
      </div>
    </draggable>
  </div>
</template>

<script>
  import draggable from 'vuedraggable'
  import ModelMixins from '@/mixins/modelMixins'
  import generateID from '@/utils/generateID'

  export default {
    name: 'ComponentList',
    mixins: [ModelMixins],
    components: {
      draggable
    },
    data () {
      return {}
    },
    methods: {
      clone (obj) {
        const genId = generateID()
        // 添加额外属性
        const extraAttr = {
          vModel: `field${genId}`,
          renderKey: +new Date()
        }

        return JSON.parse(JSON.stringify({ ...obj, ...extraAttr }))
      },
      select (element) {
        this.$emit('select', this.clone(element))
      },
      cloneComponent (origin) {
        this.$emit('clone', this.clone(origin))
        return this.clone(origin)
      }
    }
  }
</script>

<style scoped lang="scss">
  $selectedColor: #f6f7ff;
  $lighterBlue: #409EFF;
  .components-list {
    padding: 8px;
    box-sizing: border-box;
    height: 100%;

    .components-draggable {
      padding-bottom: 20px;

      .components-item {
        display: inline-block;
        width: 48%;
        margin: 1%;
        transition: transform 0ms !important;

        .components-body {
          padding: 8px 10px;
          background: $selectedColor;
          font-size: 12px;
          cursor: move;
          border: 1px dashed $selectedColor;
          border-radius: 3px;

          &:hover {
            border: 1px dashed #787be8;
            color: #787be8;
          }
        }
      }
    }
  }
</style>
